/**
 * Copyright 2009-2011 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.myjung.model.util;

import java.io.Serializable;
import java.lang.reflect.Field;

import net.myjung.Myjung;
import net.myjung.model.BaseObject;
import net.myjung.model.TransferObject;
import net.myjung.model.annotation.MdlAttribute;
import net.myjung.model.annotation.MdlElement;

import org.hibernate.engine.SessionImplementor;
import org.hibernate.id.UUIDHexGenerator;

/**
 * @author Steve M. Jung
 */
public class IdGenerator extends UUIDHexGenerator {
	public IdGenerator() {
		super();
	}
	public Serializable generate(SessionImplementor session, Object obj) {
		if ((obj instanceof BaseObject)) {
			String id = getId((BaseObject) obj);
			if (!Myjung.isEmpty(id))
				return id;
		}
		return super.generate(session, obj);
	}
	public static void populateId(BaseObject obj) {
		Field field = getIdField(obj.getClass());
		if (field == null)
			return;
		if (!field.isAccessible())
			field.setAccessible(true);
		try {
			String id = (String) field.get(obj);
			if (Myjung.isEmpty(id))
				field.set(obj, Myjung.newUId());
		} catch (IllegalArgumentException e) {
		} catch (IllegalAccessException e) {
		}

	}
	public static String getId(BaseObject obj) {
		Field field = getIdField(obj.getClass());
		if (field == null)
			return null;
		if (!field.isAccessible())
			field.setAccessible(true);
		try {
			Object id = field.get(obj);
			return id == null ? null : id.toString();
		} catch (IllegalArgumentException e) {
		} catch (IllegalAccessException e) {
		}
		return null;
	}
	public static Field getIdField(Class<?> clazz) {
		if (clazz == BaseObject.class || clazz == TransferObject.class || clazz == Object.class)
			return null;

		Field idField = getIdField(clazz.getSuperclass());
		if (idField != null)
			return idField;

		Field[] fields = clazz.getDeclaredFields();
		if (Myjung.isEmpty(fields))
			return null;
		for (Field field : fields) {
			MdlAttribute ann = field.getAnnotation(MdlAttribute.class);
			if (ann != null) {
				if (!ann.type().startsWith("id"))
					continue;
				return field;
			}
			MdlElement elemAnn = field.getAnnotation(MdlElement.class);
			if (elemAnn != null) {
				if (!elemAnn.type().startsWith("id"))
					continue;
				return field;
			}
		}
		return null;
	}
}